package com.suzhiliang.springbootlesson.loggerInterceptor;

import com.alibaba.fastjson.JSONObject;
import com.suzhiliang.springbootlesson.util.ContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Copyright (C), 2015-2018, XXX有限公司
 *
 * @ClassName: LoggerInterceptor
 * @Author: xmm
 * @Date: 2018/10/24 14:13
 * @Description: 拦截器：记录请求信息到日志表
 * 使用拦截器记录请求的日志信息
 * @Version 1.0
 */
public class LoggerInterceptor implements HandlerInterceptor {

    //请求开始时间的Key
    private static final String LOGGER_START_TIME = "logger_start_time_";

    //日志对象ENTITY的KEY
    private static final String LOGGER_ENTITY = "logger_entity_";

    /**
     * 请求入口
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //设置请求要添加到数据库的日志信息
        //获取日志实体
        LoggerEntity loggerEntity = new LoggerEntity();
        //设置请求的客户端ip地址
        loggerEntity.setLogClientIp(ContextUtils.getCliectIp(request));
        //设置请求时的方法名
        loggerEntity.setLogMethod(request.getMethod());
        //设置请求类型
        loggerEntity.setLogType(ContextUtils.getRequestType(request));
        //设置请求参数内容
        loggerEntity.setLogParamData(JSONObject.toJSONString(request.getParameterMap()));
        //设置请求开始时间到request中
        request.setAttribute(LOGGER_START_TIME, System.currentTimeMillis());
        //设置日志对象到request中
        request.setAttribute(LOGGER_ENTITY, loggerEntity);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求响应时调用方法
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        Long currentTime = System.currentTimeMillis();//当前时间
        //获取日志实体
        LoggerEntity loggerEntity = (LoggerEntity) request.getAttribute(LOGGER_ENTITY);
        //设置请求错误码
        loggerEntity.setLogHttpStatusCode(response.getStatus() + "");
        //设置请求返回时间
        loggerEntity.setLogReturnTime(currentTime + "");
        //设置请求响应的时间差
        loggerEntity.setLogTimeConsuming(currentTime - Long.valueOf(request.getAttribute(LOGGER_START_TIME).toString()));
        //设置返回对象
        loggerEntity.setLogReturnData(JSONObject.toJSONString(request.getAttribute(ContextUtils.LOGGER_RETURN)));
        //入库
        LoggerJPA loggerJPA = ContextUtils.getBeanByRequest(LoggerJPA.class, request);
        loggerJPA.save(loggerEntity);
    }
}
